import { join } from 'path'

const fs = require('fs')
const PizZip = require('pizzip')
const Docxtemplater = require('docxtemplater')
const { wordToPdf } = require('node-docto')

export async function generatePdf(data) {
  // 读取模板文件
  const templatePath = join(__dirname, '../../resources/template/xwbl.docx').replace(
    'app.asar',
    'app.asar.unpacked'
  )

  const content = fs.readFileSync(templatePath, 'binary')
  const zip = new PizZip(content)
  const doc = new Docxtemplater(zip, {
    nullGetter: function (tag) {
      return '' // 返回空字符串或其他默认值
    },
    linebreaks: true
  })

  handleData(data)
  doc.render(data)

  // 保存新的Word文档
  const newFilePath = join(__dirname, '../../resources/template/xwbl_new.docx').replace(
    'app.asar',
    'app.asar.unpacked'
  )
  const buffer = doc.getZip().generate({ type: 'nodebuffer' })
  fs.writeFileSync(newFilePath, buffer)

  const pdfPath = join(__dirname, '../../resources/template/询问笔录.pdf').replace(
    'app.asar',
    'app.asar.unpacked'
  )

  try {
    await wordToPdf(newFilePath, pdfPath, { deleteOriginal: true })
  } catch (error) {
    console.error('转换失败：', error)
  }
  return fs.readFileSync(pdfPath)
}

function handleData(data) {
  let result = ''
  if (data.text) {
    //用\n分割内容
    let tmps = data.text.split('\n')
    let lines = 0
    for (let i = 0; i < tmps.length; i++) {
      let tmp = tmps[i]
      //判断tmp长度是否为40的倍数，不足用空格补全
      let remainder = tmp.length % 40
      lines += Math.ceil(tmp.length / 40)
      if (remainder == 0) {
        result += tmp + '\n'
      } else {
        result += tmp + '   '.repeat(40 - remainder) + '\n'
      }
    }
    //删除结尾的\n
    result = result.slice(0, -1)

    let headLines = 14
    let pageLines = 44
    let pages = Math.ceil(lines / pageLines)
    let needLines = pages * pageLines - headLines - lines

    for (let i = 0; i < needLines; i++) {
      result += '  '.repeat(40) + '\n'
    }

    //删除结尾的\n
    result = result.slice(0, -1)
    data.text = result
  }
}
